package com.chris.easymallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chris.easymallproduct.entity.CategoryBrandRelationEntity;
import com.chris.easymallproduct.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chris.common.utils.PageUtils;
import com.chris.common.utils.Query;

import com.chris.easymallproduct.dao.CategoryDao;
import com.chris.easymallproduct.entity.CategoryEntity;
import com.chris.easymallproduct.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> getTreeData() {
        List<CategoryEntity> categoryEntities = this.list(new LambdaQueryWrapper<CategoryEntity>()
                .eq(CategoryEntity::getShowStatus, 1));
        return categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(node -> node.setChildren(getChildren(node, categoryEntities)))
                .sorted(Comparator.comparingInt(m -> (m.getSort() == null ? 0 : m.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void update(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.update(new UpdateWrapper<CategoryBrandRelationEntity>()
                .lambda()
                .set(CategoryBrandRelationEntity::getCatelogName, category.getName())
                .eq(CategoryBrandRelationEntity::getCatelogId, category.getCatId()));

    }

    private List<CategoryEntity> getChildren(CategoryEntity node, List<CategoryEntity> all) {
        return all.stream()
                .filter(item -> item.getParentCid().equals(node.getCatId()))
                .peek(item -> item.setChildren(getChildren(item, all)))
                .sorted(Comparator.comparingInt(m -> (m.getSort() == null ? 0 : m.getSort())))
                .collect(Collectors.toList());
    }


}